#include "StdAfx.h"

#include <time.h>
#include <iostream>
#include <fstream>
#include "SFML/Audio/SoundBuffer.hpp"
#include "SFML/Audio/Sound.hpp"
#include "Recorder.h"

#include <windows.h>
#include <tchar.h>

Recorder::Recorder(void)
{
}

Recorder::~Recorder(void)
{
}

static void SaveSamplesToFile(std::vector<short>& samples, const char* filename, bool play=false)
{
	if(samples.size())
	{
		sf::SoundBuffer soundFile;
		soundFile.LoadFromSamples((const sf::Int16*)&samples[0], samples.size(), 1, 48000);
		soundFile.SaveToFile(filename);
		if(play)
		{
			sf::Sound sound;
			sound.SetBuffer(soundFile);
			sound.Play();
		}
	}
}


void Recorder::SaveToFiles()
{
	//create a new folder with current time as its name	  
	time_t rawtime;
	time (&rawtime);  
	struct tm timeinfoS;
	struct tm* timeinfo = &timeinfoS;
	localtime_s (&timeinfoS, &rawtime);
	TCHAR wdirname[17];
	wsprintf(wdirname, _T("%d-%d-%d-%d-%d\0"), timeinfo->tm_year+1900, timeinfo->tm_mon+1,
		timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min);
	CreateDirectory(wdirname, NULL);

	char dirname[18];
	sprintf_s(dirname, "%d-%d-%d-%d-%d\\\0", timeinfo->tm_year+1900, timeinfo->tm_mon+1,
		timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min);
	char modFile[32];
	char carrierFile[30];
	char vocoderFile[30];
	char pitchFile[27];
	sprintf_s(modFile, "%smodulator.wav\0", dirname);
	sprintf_s(carrierFile, "%scarrier.wav\0", dirname);
	sprintf_s(vocoderFile, "%svocoder.wav\0", dirname);
	sprintf_s(pitchFile, "%spitch.txt\0", dirname);

	//save each sample vector to a wav file
	SaveSamplesToFile(modulatorSamples, modFile);
	SaveSamplesToFile(carrierSamples, carrierFile);
	SaveSamplesToFile(vocoderSamples, vocoderFile, true);
	modulatorSamples.clear();
	carrierSamples.clear();
	vocoderSamples.clear();
}